import 'dart:io';

import 'package:eshi/app/shi/data/HistoryMarks.dart';
import 'package:eshi/app/shi/data/parse/IndentParser.dart';
import 'package:flutter/material.dart';
import 'package:eshi/app/CommonFunctions.dart';
import 'package:eshi/main.dart';
import 'package:eshi/app/shi/data/History.dart';
import 'package:eshi/app/shi/data/HistoryPoint.dart';
import 'package:eshi/app/shi/data/SearchResult.dart';
import 'package:eshi/app/shi/data/System.dart';
import 'package:eshi/app/shi/data/parse/FileParser.dart';
import 'package:eshi/app/shi/tabs.dart';
import 'package:eshi/app/shi/taxis.dart';
import 'package:eshi/app/shi/taxis/CustomSearchDelegate.dart';

mixin TAxisEvent on State<TimeAxisWidget>{
  /// 右下角时间轴按钮的单击事件
  /// 显示时间轴
  void onTimeLineButtonClick(){
      setState(() {
        if((this as TimeAxisState).isTVisible){
          (this as TimeAxisState).isTVisible = false;
          return;
        }
        (this as TimeAxisState).showTimeLine();
        mainWidgetKey.currentState?.setButtonShow(false);
      });
  }
  /// 通过时间轴更新朝代
  void onTimeLineClick(HistoryPoint point){
        setState(() {
          (this as TimeAxisState).currentPoint = point;
        });
  }

  /// 通过页面上下翻动更新朝代
  void onPageDraw(HistoryPoint point){
     (this as TimeAxisState).currentPoint = point;
  }

  // 处理返回事件
  Future<bool> handleWillPop () async {
    var self = this as TimeAxisState;
      // 如果遮罩层显示，关闭遮罩层而不返回页面
      if (self.isTVisible) {
        setState(() {
           self.isTVisible = false;
        });
        mainWidgetKey.currentState?.setButtonShow(true);
        return false; // 阻止页面返回
      }
      return true;
  }

  //历史点修改事件
  void onPointChange(HistoryPoint point,{required String data,Map<String,List<String>>? marks}) {
      //是新增 
      if(point.data.isEmpty){
          data="${point.name}\n${data.split("\n").map((v) => IndentParser.sp+v).join("\n")}\n";
          point.parseName();
      }
      //是删除
      if(data.isEmpty){
          point.enable = false;
      }
      //保存
      point.source = "${data.trim()}\n";
      if(marks!=null && marks.isNotEmpty){
        marks.forEach((k,v){
          point.history?.addMark(k,v);
        });
      }
      setState(() {
        self.currentPoint = point;
      });
      point.history?.save(point:point);
  }
  /// 分享
  void onShare(History history) {
    // System.open(FileParser.getWholeName("assets/image","actions"));
    // return;
     msg("${mt("数据组织中")}...");
     final data = history.toString();
     final name =  history.name;
     List<String> files = [];
     history.marks.forEach((k,v){
       if(v != HistoryMarks.baike){ 
        var file = FileParser.getWholeName("assets/${v.name}",k);
        if(file.isNotEmpty) {
          files.add(file);
        }
       }
     });
     for (var v in history.useAssets) {
        var [type,name] = v.split(".");
        if(type=="img") type = "image";
        var file = FileParser.getWholeName("assets/$type",name);
        if(file.isNotEmpty) files.add(file);
     }
    FileParser.buildDtt(name,data,files).then((File file){
        msg("${mt("数据组织完成")}！");
        System.open(file.path,androidContentEnable: true);
    });
  }
  TimeAxisState get self{
    return this as TimeAxisState;
  }
  History get history => self.widget.data;
  /// 定位节点并显示通过搜索的关键字  
  onSearchIndex(String key, {int index=0, required tabsState? state}) {
    final result = HistorySearchResult.search(key,index);
    final pointResult = result.pointResult;
    //设置节点的顺序防止手动拖拽乱跳 
    self.widget.index = result.point.index;  
    //显示当前节点 
    state?.setPoint(result.point);
    //设置tabIndex与选择index
    state
      ?..switchTab(pointResult.tabIndex)
      ..selectText(pointResult.pageIndex);
  }

  // 点击搜索按钮，显示搜索框
  SearchResult? lastSearchResult;
  Future<SearchResult> onSearch() async{  
    String? key=lastSearchResult?.key;
    key = await showSearch(context: context, delegate: CustomSearchDelegate(key));
    var count = 0;
    if (key != null && key.isNotEmpty) {
        count= history.searchKey(key);
    }
    lastSearchResult = SearchResult(count,key!);
    return lastSearchResult!;
  }
}
